package com.lwm.service.impl;

import cn.hutool.core.util.IdUtil;
import com.lwm.domain.DeliveryOrder;
import com.lwm.domain.ResponseResult;
import com.lwm.dto.DeliveryOrderDto;
import com.lwm.dto.PageParams;
import com.lwm.mapper.DeliveryOrderMapper;
import com.lwm.service.DeliveryOrderServiceImpl;
import com.lwm.utils.Code;
import com.lwm.utils.HintMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DeliveryOrderService implements DeliveryOrderServiceImpl {
    @Resource
    private DeliveryOrderMapper deliveryOrderMapper;

    @Override
    public ResponseResult<Object> save(DeliveryOrder deliveryOrder) {
        deliveryOrder.setId(IdUtil.getSnowflakeNextId());
        if(deliveryOrder.getIsDeleted() == null ) deliveryOrder.setIsDeleted(0);
        deliveryOrderMapper.insert(deliveryOrder);
        return new ResponseResult<>(Code.SAVE_OK, HintMessage.SAVE_OK_HINT);
    }

    @Override
    public ResponseResult<Object> removeBatch(List<Long> ids) {
        deliveryOrderMapper.removeBatch(ids);
        return new ResponseResult<>(Code.DELETE_OK, HintMessage.REMOVE_OK_HINT);
    }

    @Override
    public ResponseResult<Object> updateById(DeliveryOrder deliveryOrder) {
        if(deliveryOrder.getId() == null) return new ResponseResult<>(Code.UPDATE_ERR, HintMessage.EDIT_ERR_HINT);
        deliveryOrderMapper.update(deliveryOrder);
        return new ResponseResult<>(Code.UPDATE_OK, HintMessage.EDIT_OK_HINT);
    }

    @Override
    public ResponseResult<Object> getPage(DeliveryOrderDto deliveryOrderDto) {
        System.out.println(deliveryOrderDto.getPage());
        if(deliveryOrderDto.getSize() == null) deliveryOrderDto.setSize(10);
        if(deliveryOrderDto.getPage() == null) deliveryOrderDto.setPage(1);
        // 拿到总条数
        Long total = deliveryOrderMapper.getTotal(deliveryOrderDto);
        // 拿到最大页码
        Double maxPage = Math.ceil(Double.valueOf(total) / Double.valueOf(deliveryOrderDto.getSize()));
        // 求当前页码
        Integer currentPage = maxPage.intValue() < deliveryOrderDto.getPage() ? maxPage.intValue() : deliveryOrderDto.getPage();
        currentPage = currentPage <= 0 ? 1 : currentPage;
        // 求开始的页码
        Integer startPage = (currentPage - 1) * deliveryOrderDto.getSize();
        deliveryOrderDto.setPage(startPage);

        List<DeliveryOrder> page = deliveryOrderMapper.getPage(deliveryOrderDto);
        PageParams listPageParams = new PageParams(currentPage, deliveryOrderDto.getSize(), total.intValue(), page);
        return new ResponseResult<>(Code.GET_OK, HintMessage.GET_OK_HINT, listPageParams);
    }

    @Override
    public ResponseResult<Object> getAll() {
        List<DeliveryOrder> all = deliveryOrderMapper.getAll();
        return new ResponseResult<>(Code.GET_OK, HintMessage.GET_OK_HINT, all);
    }

    public DeliveryOrder getById(Long id) {
        return deliveryOrderMapper.getById(id);
    }
}
